const { sqlite3 } = require('../../mysql')

// 管理平台获取公告列表数据
const getNotice = async (ctx) => {
  let formData = ctx.query
  let offset = (formData.page - 1) * formData.limit
  let keyword = formData.keyword
  let limitdata = {}
  let data = {}
  if (keyword) {
    data = await sqlite3('notice')
      .where('title', 'LIKE', '%' + keyword + '%')
      .andWhere('is_delete', 0)
      .orderBy('id', 'desc')
      .select()
      .limit(formData.limit)
      .offset(offset)
    total = data.length
  } else {
    limitdata = await sqlite3('notice').count({ total: '*' })
    data = await sqlite3('notice')
      .where('is_delete', 'LIKE', 0)
      .orderBy('id', 'desc')
      .select()
      .limit(formData.limit)
      .offset(offset)
    total = limitdata[0].total
  }
  if (data) {
    ctx.body = {
      code: 200,
      item: data,
      total,
      result: true,
    }
  } else {
    ctx.body = {
      code: false,
    }
  }
}

// 管理平台添加公告数据
const createNotice = async (ctx) => {
  console.log('create.ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('notice').insert(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 管理平台更新公告数据
const updateNotice = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('notice')
    .where('id', formData.id)
    .update(formData)
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 管理平台删除公告数据
const deleteNotice = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('posts')
    .where('ID', formData.ID)
    .update('post_status', 'trash')
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

module.exports = { getNotice, createNotice, updateNotice, deleteNotice }
